<?php

namespace app\admin\controller;

use think\Controller;
use think\facade\Session;
use Util\Sysdb;
use app\admin\model\Menttype as ReimbursementType;

class Menttype extends BaseAdmin
{
    public function typelist(){
        $typelist = new ReimbursementType();
        $count = $typelist->count();
        $res = $typelist->orderRaw('IFNULL(update_time,create_time) desc')->paginate(10);
        $this->assign([
           'count'=>$count,
           'res'=>$res,
        ]);
        return view('list');
    }

    //添加
    public function addtype(){
        if (request()->ispost()) {
            $data = [
                'type_name'     => !empty(input('type_name')) ? trim(match_chinese(input('type_name'))) : '',
                'create_time'  => time(),
            ];

            $typelist = new ReimbursementType();
            $add = $typelist::insert($data);
            if ($add) {
                return json(['code' => 200, 'msg' => '添加成功']);
            } else {
                return json(['code' => 500, 'msg' => '添加失败']);
            }
        }
        return view('add');
    }

    //修改
    public function edittype()
    {
        $typelist = new ReimbursementType();
        if(request()->ispost()){
            $data = input('post.');
            $data['type_name'] = !empty(input('type_name')) ? trim(match_chinese(input('type_name'))) : '';
            $data['update_time'] = time();
            $edit = $typelist->allowField(true)->update($data);
            if($edit){
                return json(['code' => 200,'msg' => '修改成功']);
            }else{
                return json(['code' => 500,'msg' => '修改失败']);
            }
        }
        $user = $typelist::find(input('id'));
        $this->assign(['user' => $user]);
        return view('edit');
    }

    //删除
    public function typedel(){
        $typelist = new ReimbursementType();
        $id = (int)input('post.id');
        $res = $typelist::where('id',$id)->delete();
        if (!$res) {
            exit(json_encode(array('code' => 1, 'msg' => '删除失败')));
        }
        exit(json_encode(array('code' => 0, 'msg' => '删除成功')));
    }
}